package com.lazy.example.simpledecoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author <a href="mailto:norman.maurer@googlemail.com">Norman Maurer</a>
 */
public class FixedLengthFrameDecoder extends ByteToMessageDecoder {
    protected static final Logger logger = LoggerFactory.getLogger(ByteBufEchoHandler.class);
    private final int frameLength;
    Object object;

    public FixedLengthFrameDecoder(int frameLength, Object object) {
        if (frameLength <= 0) {
            throw new IllegalArgumentException(
                    "frameLength must be a positive integer: " + frameLength);
        }
        this.frameLength = frameLength;
        this.object = object;
        logger.info("FixedLengthFrameDecoder@{} object:{}", this.hashCode(), object.hashCode());
    }

    public FixedLengthFrameDecoder(int frameLength) {
        if (frameLength <= 0) {
            throw new IllegalArgumentException(
                    "frameLength must be a positive integer: " + frameLength);
        }
        this.frameLength = frameLength;
        logger.info("FixedLengthFrameDecoder@{}", this.hashCode());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        logger.info("channelActive FixedLengthFrameDecoder@{} object:{}", this.hashCode(), object.hashCode());
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        logger.info("decoded FixedLengthFrameDecoder@{}, {}@{}", this.hashCode(), ctx.getClass(), ctx.hashCode());
        if (in.readableBytes() >= frameLength) {
            ByteBuf buf = in.readBytes(frameLength);
            out.add(buf);
        }
    }
}
